#!/usr/bin/env python
# -*- coding: utf-8 -*-

import web
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

db = web.database(dbn='mysql', db='wiki', user='root', passwd='root',charset='utf8',unix_socket='/usr/local/mysql/sock/mysql.sock')

def get_pages():
    return db.select('pages', order='id DESC')

def get_count():
	results = db.query("SELECT COUNT(*) AS total_pages FROM pages")
	return results[0].total_pages

def get_page_by_url(url):
    try:
        return db.select('pages', where='url=$url', vars=locals())[0]
    except IndexError:
        return None

def get_page_by_id(id):
    try:
        return db.select('pages', where='id=$id', vars=locals())[0]
    except IndexError:
        return None

def new_page(url, title, text):
    db.insert('pages', url=url, title=title, content=text)

def del_page(id):
    db.delete('pages', where="id=$id", vars=locals())

def update_page(id, url, title, text):
    db.update('pages', where="id=$id", vars=locals(),
        url=url, title=title, content=text)


#=================================================================
# for table files

def get_file_by_name(name):
	try:
		return db.select('files',where='name=$name',vars=locals())[0]
	except IndexError:
		return None

def get_all_files():
	return db.select('files',order='id DESC')

def del_file(name):
	db.delete('files',where='name=$name',vars=locals())

def add_file(path,name,modifytime,memo):
	db.insert('files',path=path,name=name,modifytime=modifytime,memo=memo)

def update_file(id,name,modifytime,memo):
	db.update('files',where="name=$name",vars=locals(),modifytime=modifytime,memo=memo)

